package com.maoye.ossp.biz.brand.controller;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.hotent.base.api.query.Direction;
import com.hotent.base.api.query.FieldSort;
import com.hotent.base.api.query.QueryFilter;
import com.hotent.base.api.query.QueryOP;
import com.hotent.base.core.util.string.StringUtil;
import com.hotent.base.db.api.IdGenerator;
import com.hotent.base.db.model.DefaultQueryFilter;
import com.hotent.base.db.mybatis.domain.DefaultFieldSort;
import com.hotent.base.db.mybatis.domain.DefaultPage;
import com.maoye.ossp.biz.brand.entity.Supplier;
import com.maoye.ossp.biz.brand.entity.SupplierBank;
import com.maoye.ossp.biz.brand.entity.SupplierRegister;
import com.maoye.ossp.biz.brand.service.IBrandKeygenService;
import com.maoye.ossp.biz.brand.service.ISupplierRegisterService;
import com.maoye.ossp.biz.brand.service.ISupplierService;
import com.maoye.ossp.biz.brand.utils.BrandCommonConstant;
import com.maoye.ossp.biz.brand.utils.BrandUtils;
import com.maoye.ossp.common.entity.Page;
import com.maoye.ossp.common.util.DateUtils;
import com.maoye.ossp.common.util.ReflectionUtils;
import com.maoye.ossp.common.web.BaseController;
import com.maoye.ossp.sys.base.utils.SysDictUtils;
import com.maoye.ossp.sys.org.util.UserUtils;
import com.maoye.sc.api.domain.User;
import com.maoye.sc.service.user.UserServiceImpl;

/**
 * 对象功能:供应商基本信息 控制器类
 *开发公司:maoye shenzhen 
 *开发人员:lyf 
 *创建时间:2013-09-30 10:04:52
 */
@Controller
@RequestMapping("/biz/brand/supplier/")
public class SupplierController extends BaseController {
	@Resource
	private ISupplierService supplierService;
	@Resource
	private ISupplierRegisterService supplierRegisterService;
	@Resource
	public IBrandKeygenService keygenService;
	@Resource
	public IdGenerator idGenerator;
	@Resource
	public UserServiceImpl userServiceImpl;
	@RequestMapping("list")
	public String list(Supplier supplier, HttpServletRequest request,
			HttpServletResponse response, Model model) {
		QueryFilter queryFilter = getQuerFilter(request, supplier);
		Page<Supplier> page = supplierService.find(queryFilter);
		model.addAttribute("page", page);
		return resultPage("/biz/brand/supplier/list", model, request);
	}
	
	@RequestMapping(value = "save")
	public String save(Supplier supplier,Model model,HttpServletRequest request) {
		try 
		{
			String msg = supplierService.save(supplier);
			if (null != msg && !"".equals(msg))
			{
				addMessage(model, msg);
			}else
			{
				model.addAttribute("tabId", "bus");
				//addMessage(model, BrandCommonConstant.MSG_2001);
			}
			
		} catch (Exception e) {
			addMessage(model, BrandCommonConstant.EX_1009);
		}
		String navId = request.getParameter("navId");
		String reJsp = request.getParameter("reJsp");
		reJsp = reJsp == null ? "list" : "userinfo";
		model.addAttribute("reJsp", reJsp);
		model.addAttribute("navId", navId);
		setSupplierInfo(supplier, model);
		return "/biz/brand/supplier/apply";
	}

	@RequestMapping(value = "submit")
	public String submit( Model model,Supplier supplier,RedirectAttributes redirectAttributes,HttpServletRequest request,HttpServletResponse response) throws Exception {
		//Supplier getsupplier = supplierService.get(supplier.getId());
		supplierService.submit(supplier);
		addMessage(redirectAttributes, "提交'" + supplier.getCname()+ "供应商'成功");
		String navId = request.getParameter("navId");
		return "redirect:/biz/brand/supplier/list?navId="+navId;
	}
	
	/**
	 * 添加供应商基本信息
	 * 
	 * @param brandLevel
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "add")
	public String add(Supplier supplier, Model model,HttpServletRequest request) {
		supplier.setViceId(idGenerator.getUId());
		String navId = request.getParameter("navId");
		String reJsp = request.getParameter("reJsp");
		reJsp = reJsp == null ? "list" : "userinfo";
		model.addAttribute("reJsp", reJsp);
		model.addAttribute("navId", navId);
		model.addAttribute("supplier", supplier);
		model.addAttribute("supplierRegister", new SupplierRegister());
		model.addAttribute("supplierBank", new SupplierBank());
		return "/biz/brand/supplier/apply";
	}

	/**
	 * 供应商准入
	 * @param supplier
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "apply")
	public String apply(Supplier supplier, Model model,HttpServletRequest request,
			HttpServletResponse response) 
	{
		supplier = supplierService.get(UserUtils.getCurrentUserId());
		if(null == supplier)
		{
			supplier = new Supplier();
		}
		String navId = request.getParameter("navId");
		String reJsp = request.getParameter("reJsp");
		reJsp = reJsp == null ? "list" : "userinfo";
		model.addAttribute("reJsp", reJsp);
		model.addAttribute("navId", navId);
		setSupplierInfo(supplier, model);
		model.addAttribute("supplier", supplier);
		return "/biz/brand/supplier/apply";
	}
	
	@RequestMapping(value = "{id}/delete")
	public String delete(@PathVariable String id, Model model,
			RedirectAttributes redirectAttributes,HttpServletRequest request) {
		try {
			//删除单个供应商信息
			supplierService.delByPk(Long.valueOf(id));
			addMessage(redirectAttributes, BrandCommonConstant.MSG_2006);
		} catch (Exception e) {
			addMessage(redirectAttributes, BrandCommonConstant.EX_1012);
			e.printStackTrace();
		}
		String navId = request.getParameter("navId");
		return "redirect:/biz/brand/supplier/list?navId="+navId;
	}

	@RequestMapping(value = "deleteAll")
	public String deleteAll(HttpServletRequest request,
			HttpServletResponse response, Model model,RedirectAttributes redirectAttributes) 
	{
		try {
			String deleteIds = request.getParameter("deleteIds");
			Long[] lAryId = BrandUtils.getLongAryByStr(deleteIds,";");
			for(Long id : lAryId)
			{
				supplierService.delByPk(id);
			}
			addMessage(redirectAttributes, BrandCommonConstant.MSG_2006);
		}catch(Exception e)
		{
			addMessage(redirectAttributes, BrandCommonConstant.EX_1012);
			e.printStackTrace();
		}
		String navId = request.getParameter("navId");
		return "redirect:/biz/brand/supplier/list?navId="+navId;
	}
	
	@RequestMapping(value = "{id}/view")
	public String view(@PathVariable String id, Model model, HttpServletRequest request) {
		Supplier supplier = supplierService.get(Long.valueOf(id));
		String navId = request.getParameter("navId");
		model.addAttribute("navId", navId);
		model.addAttribute("supplier", supplier);
		return "/biz/brand/supplier/view";
	}

	@RequestMapping(value = "{id}/edit")
	public String edit(@PathVariable String id, Model model, HttpServletRequest request) {
		Supplier supplier = supplierService.get(Long.valueOf(id));
		setSupplierInfo(supplier, model);
		String navId = request.getParameter("navId");
		model.addAttribute("navId", navId);
		model.addAttribute("supplier", supplier);
		return "/biz/brand/supplier/apply";
	}
	
	@RequestMapping(value = "userinfo")
	public String userinfo(Supplier supplier,Model model, HttpServletRequest request,HttpServletResponse response) {
		
		User user = userServiceImpl.getUserByAccountID(UserUtils.getCurrentAccountId().toString());
		if(null != user && "SUPPLIER".equals(user.getUserType()))
		{
			supplier = supplierService.get(user.getId());
		}else
		{
			model.addAttribute("supplier", supplier);
			return list(supplier, request, response, model);
		}
		String navId = request.getParameter("navId");
		model.addAttribute("navId", navId);
		model.addAttribute("supplier", supplier);
		return "/biz/brand/supplier/userinfo";
	}
	
	/**
	 * 加载供应商列表
	 * @param supplier
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 * @author yangh
	 * @data 2014年5月5日
	 */
	@RequestMapping("suppInfoPage")
	public String suppInfoPage(Supplier supplier, HttpServletRequest request,
			HttpServletResponse response, Model model) {
			QueryFilter queryFilter = getQuerFilter(request,supplier);
			if(StringUtil.isNotEmpty(supplier.getCname())){
				queryFilter.addFilter("cname", supplier.getCname(), QueryOP.LIKE);
			}
			if(StringUtil.isNotEmpty(supplier.getSupplierNo())){
				queryFilter.addFilter("supplierNo", supplier.getSupplierNo(), QueryOP.LIKE);
			}
			Page<Supplier> page = (Page<Supplier>) supplierService.find(queryFilter);
			int totalSize = (page.getTotal() + page.getPageSize() - 1) / page.getPageSize();
			model.addAttribute("page", page);
			model.addAttribute("totalSize", totalSize);
			return "/biz/contract/common/supplierList";
	}
/**
 * 分页查询供应商信息(在弹出层展示)
 * @param supplier
 * @param request
 * @param response
 * @param model
 * @author llz
 * @throws Exception 
 * @data 2014年5月5日
 */
	@RequestMapping("suppInfoList")
	public void listToContract(Supplier supplier, HttpServletRequest request,
			HttpServletResponse response, Model model) throws Exception {
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/plain");
		PrintWriter out = response.getWriter();
		QueryFilter queryFilter = getQuerFilter(request,supplier);
		if(StringUtil.isNotEmpty(supplier.getCname())){
			queryFilter.addFilter("cname", supplier.getCname(), QueryOP.LIKE);
		}
		if(StringUtil.isNotEmpty(supplier.getSupplierNo())){
			queryFilter.addFilter("supplierNo", supplier.getSupplierNo(), QueryOP.EQUAL);
		}
		Page<Supplier> page = (Page<Supplier>) supplierService.find(queryFilter);
		List<Supplier> list = page.getList();
		StringBuffer sb = new StringBuffer(); 
		sb.append("{\"total\":\""+page.getTotal()+"\",");
		sb.append("\"pageNo\":\""+page.getPageNo()+"\",");
		sb.append("\"pageSize\":\""+page.getPageSize()+"\",");
		sb.append("\"jsonRoot\":[");
		
		for(int i = 0;i<list.size();i++){
			Supplier supp = list.get(i);
			
			String levelValue = SysDictUtils.getValue("SUPPLIER_LEVEL", supp.getSupplierLevel());
			String statusValue = SysDictUtils.getValue("SUPPLIER_STATUTS", supp.getSupplierStatus());
			String supplierTypeValue = SysDictUtils.getValue("supplierType", supp.getSupplierType());
			String qualityValue = SysDictUtils.getValue("SUPPLIER_QUALITY", supp.getQuality());
			if(levelValue ==null){
				levelValue ="";
			}
			if(statusValue ==null){
				statusValue ="";
			}
			if(supplierTypeValue ==null){
				supplierTypeValue ="";
			}
			if(qualityValue ==null){
				qualityValue ="";
			}
			sb.append("{\"id\":\""+ supp.getId());  
            sb.append("\",");
            sb.append("\"cname\":\""+ supp.getCname());  
            sb.append("\",");
            sb.append("\"supplierType\":\""+ supp.getSupplierType());  
            sb.append("\",");
            sb.append("\"supplierTypeValue\":\""+ supplierTypeValue);  
            sb.append("\",");
            sb.append("\"supplierLevel\":\""+ supp.getSupplierLevel());  
            sb.append("\",");
            sb.append("\"levelValue\":\""+levelValue);  
            sb.append("\",");
            sb.append("\"status\":\""+ supp.getSupplierStatus());  
            sb.append("\",");
            sb.append("\"statusValue\":\""+statusValue);  
            sb.append("\",");
            sb.append("\"quality\":\""+ supp.getQuality());  
            sb.append("\",");
            sb.append("\"qualityValue\":\""+ qualityValue);  
            sb.append("\",");
            sb.append("\"supplierNo\":\""+ supp.getSupplierNo());  
            sb.append("\"");  
            sb.append("},"); 
		}
		if(list.size()>0){
			sb.deleteCharAt(sb.lastIndexOf(","));
		}
		  // 删去最后一个逗号  
        sb.append("]}"); 
        out.print(sb);
        out.flush();
		out.close();
		
	}
	
	@RequestMapping("dialoglist")
	public String dialoglist(Supplier supplier, HttpServletRequest request,
			HttpServletResponse response, Model model) {
		QueryFilter queryFilter = getQuerFilter(request, supplier);
		Page<Supplier> page = supplierService.find(queryFilter);
		model.addAttribute("page", page);
		return resultPage("/biz/brand/supplier/modalSupplierList", model, request);
	}
	
	@RequestMapping(value = "{id}/sap")
	public String sendSap(@PathVariable String id, Model model,
			RedirectAttributes redirectAttributes, HttpServletRequest request) {
		Supplier supplier = supplierService.get(Long.valueOf(id));
		String msg = "";
		try
		{
			msg = supplierService.sendToSAP(supplier);
		}catch(Exception e)
		{
			msg = BrandCommonConstant.EX_1008+e.getCause();
		}
		String navId = request.getParameter("navId");
		model.addAttribute("navId", navId);
		addMessage(redirectAttributes, msg);
		model.addAttribute("supplier", supplier);
		model.addAttribute("msg", msg);
		return "/biz/brand/supplier/view";
	}
	
	@RequestMapping(value = "sapAll")
	public String sendSapAll(HttpServletRequest request,
			HttpServletResponse response, Model model,RedirectAttributes redirectAttributes)  {
		String sendIds = request.getParameter("sendIds");
		Long[] ids = BrandUtils.getLongAryByStr(sendIds,";");
		String msg = "";
		try
		{
			msg = supplierService.sendToSAP(ids);
		}catch(Exception e)
		{
			e.printStackTrace();
			msg = BrandCommonConstant.EX_1008+e.getCause();
		}
		String navId = request.getParameter("navId");
		addMessage(redirectAttributes, msg);
		return "redirect:/biz/brand/supplier/list?navId="+navId;
	}
	
	@RequestMapping(value = "synchroniSap")
	public String synchroniSap(HttpServletRequest request,
			HttpServletResponse response, Model model,RedirectAttributes redirectAttributes)  {
		String msg = "";
		try
		{
			msg = supplierService.synchroniSap(new Supplier());
		}catch(Exception e)
		{
			e.printStackTrace();
			msg = BrandCommonConstant.EX_1008+e.getCause();
		}
		addMessage(redirectAttributes, msg);
		return "redirect:/biz/brand/excel/syn";
	}
	
	private void setSupplierInfo(Supplier supplier,Model model)
	{
		if(null == supplier.getSupplierRegister())
		{
			supplier.setSupplierRegister(new SupplierRegister());
			supplier.getSupplierRegister().setSupplierAccountId(supplier.getId());
		}
		if(null == supplier.getSupplierBank())
		{
			supplier.setSupplierBank(new SupplierBank());
			supplier.getSupplierBank().setSupplierId(supplier.getId());
			supplier.getSupplierBank().setSupplierBankList(supplier.getSupplierBankList());
		}
		model.addAttribute("supplierBank", supplier.getSupplierBank());
		model.addAttribute("supplierRegister", supplier.getSupplierRegister());
	}
	
	/**
	 * 返回构建的QueryFilter
	 * 
	 * @param request
	 * @param model
	 * @return
	 */
	protected QueryFilter getQuerFilter(HttpServletRequest request,
			Supplier model) {
		DefaultQueryFilter queryFilter = new DefaultQueryFilter();
		try {
			String pageSize = request.getParameter("pageSize");
			String pageNo = (String) request.getParameter("pageNo");
			// 设置查询字段
			setQueryParam(request, queryFilter, model);
			// 设置分页
			if (StringUtil.isNotEmpty(pageSize)
					&& StringUtil.isNotEmpty(pageNo)) {
				DefaultPage page = new DefaultPage();
				page.setLimit(Integer.parseInt(pageSize));
				page.setPage(Integer.parseInt(pageNo));
				queryFilter.setPage(page);
			} else if (StringUtil.isNotEmpty(pageSize)) {
				DefaultPage page = new DefaultPage();
				page.setLimit(Integer.parseInt(pageSize));
				queryFilter.setPage(page);
			}
			// 设置排序字段
			String sort = request.getParameter("sort");
			String order = request.getParameter("order");
			if (StringUtil.isNotEmpty(sort) && StringUtil.isNotEmpty(order)) {
				List<FieldSort> fieldSorts = new ArrayList<FieldSort>();
				fieldSorts.add(new DefaultFieldSort(sort, Direction
						.fromString(order)));
				queryFilter.setFieldSortList(fieldSorts);
			}
		} catch (Exception e) {
		}
		return queryFilter;
	}

	/**
	 * 设置查询字段
	 * 
	 * @param request
	 * @param queryFilter
	 * @param model
	 */
	protected void setQueryParam(HttpServletRequest request,
			DefaultQueryFilter queryFilter, Supplier model) {
		if (model != null) {
			Enumeration params = request.getParameterNames();
			while (params.hasMoreElements()) {
				String key = params.nextElement().toString();
				Object value = ReflectionUtils.getFieldValueByName(key, model);
				if (value != null && StringUtils.isNotBlank(value.toString())) {
					if (value instanceof Date) {
						value = DateUtils.formatDate((Date) value);
					}
					queryFilter.getParams().put(key, value);
				}
			}
		}
	}
	
}